package retrieval;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;

import utils.ThreadCritical;

/**
 * 用于同步访问文件夹的封装类
 * 
 * @author eDisOn
 * 
 */

import utils.Configuration;

public class DirWrapper
{
    private static DirWrapper   dirWrapper     = null;
    ThreadCritical              threadCritical = null;

    private static final String ROOT           = Configuration.RootPath;
    private String              path           = ROOT + Configuration.RETRIVAL.FilePath;

    public static DirWrapper getInstance()
    {
        if (dirWrapper == null)
        {
            dirWrapper = new DirWrapper();
        }
        return dirWrapper;
    }

    private DirWrapper()
    {
        this.threadCritical = new ThreadCritical();
    }

    public boolean save(byte[] streams, String fileName)
    {
        threadCritical.getLock();
        try
        {
            FileWriter fw = new FileWriter(this.path + fileName);
            PrintWriter fpw = new PrintWriter(fw);

            StringBuffer strBuf = new StringBuffer();
            for (byte ch : streams)
            {
                strBuf.append((char) ch);
            }
            String content = strBuf.toString();
            fpw.print(content);
            fpw.flush();
            fw.close();
            return true;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
        finally
        {
            threadCritical.releaseLock();
        }
    }

    public File[] listFiles(String dir)
    {
        try
        {
            threadCritical.getLock();
            File[] files = new File(dir).listFiles();
            return files;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
        finally
        {
            threadCritical.releaseLock();
        }
    }
}
